package com.itheima.reggie.controller;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        String accesskeyId = "LTAI5tFboYEZRVmS9WSjUP4y";
        String accesskeySecret = "9fgzFInuN1Qi8PD0iMTBmMLkFlM47T";
        String bucketName = "reggieimg";

        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accesskeyId, accesskeySecret);
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            filename = filename + uuid;
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            filename = dataPath + "/" + filename;
            ossClient.putObject(bucketName, filename, inputStream);
            ossClient.shutdown();
            String url = "https://" + bucketName + "." + endpoint + "/" + filename;
            return R.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }




        /*String rand = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = rand + substring;
        File file1 = new File(basePath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+fileName));
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("文件上传失败");
        }*/
    }

    /*@GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath, name));
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream, outputStream);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
